/*
 * Lenovo Group
 * Copyright (c) 2015-2016 All Rights Reserved.
 * Project Name: lmrp-android app
 * Create Time: 16-3-9 下午1:22
 */

package com.lenovo.mso2o.ui.fragment;

/**
 * Created by hippo on 12/3/15.
 */

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMChatOptions;
import com.lenovo.framework.base.ActionBarFragment;
import com.lenovo.framework.base.ActionBarFragmentActivity;
import com.lenovo.framework.biz.ContextManager;
import com.lenovo.framework.conf.FConstants;
import com.lenovo.framework.util.DLog;
import com.lenovo.framework.util.FPreferenceManager;
import com.lenovo.framework.util.FileHelper;
import com.lenovo.framework.util.ViewHelper;
import com.lenovo.mso2o.BuildConfig;
import com.lenovo.mso2o.MSApplication;
import com.lenovo.mso2o.R;
import com.lenovo.mso2o.conf.MSConstants;
import com.lenovo.mso2o.service.UploadService;
import com.lenovo.mso2o.ui.WebActivity;
import com.lenovo.framework.util.FileSizeHelper;
import com.umeng.update.UmengUpdateAgent;
import com.umeng.update.UmengUpdateListener;
import com.umeng.update.UpdateResponse;
import com.umeng.update.UpdateStatus;

import java.util.ArrayList;

import butterknife.Bind;

/**
 * 设置
 */
public class AppSettingFragment extends ActionBarFragment implements CheckBox.OnCheckedChangeListener, View.OnClickListener, ConfirmDialogFragment.DialogClickListener, UmengUpdateListener {
    private static final String UPDATE_TAG = "upgrade";
    @Bind(R.id.relative_cutSetting)
    RelativeLayout cutsetting;
    @Bind(R.id.relative_upgrade)
    RelativeLayout update;
    @Bind(R.id.relative_clearCache)
    RelativeLayout clearcache;
    @Bind(R.id.relative_feedBack)
    RelativeLayout feedback;
    @Bind(R.id.tv_update_mindIcon)
    TextView tv_updateIcon;
    @Bind(R.id.tv_currentVersion)
    TextView tv_currentVersion;
    private UpdateResponse updateResponse;

    public static AppSettingFragment newInstance() {
        AppSettingFragment fragment = new AppSettingFragment();
        return fragment;
    }

    public AppSettingFragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        ArrayList<View> list = ViewHelper.getAllChildren(view);
        int i = 0;
        for (View v : list) {
            if (v instanceof CheckBox) {
                ((CheckBox) v).setOnCheckedChangeListener(this);
                //related with ui xml
                if(MSConstants.KEY_UPLOAD_MODE_WIFI_ONLY.equals(v.getTag())) {
                    ((CheckBox) v).setChecked(FPreferenceManager.getBoolean("" + v.getTag(), false));
                }else{
                    ((CheckBox) v).setChecked(FPreferenceManager.getBoolean("" + v.getTag(), true));
                }
            }
        }
        cutsetting.setOnClickListener(this);
        clearcache.setOnClickListener(this);
        feedback.setOnClickListener(this);
        tv_updateIcon.setVisibility(View.GONE);
        tv_currentVersion.setText(BuildConfig.VERSION_NAME + "." + (BuildConfig.VERSION_CODE%100));
        //changeTheme.setOnClickListener(this);
        UmengUpdateAgent.setUpdateAutoPopup(false);
        UmengUpdateAgent.setUpdateListener(this);
        UmengUpdateAgent.update(this.getContext());
        return view;
    }

    @Override
    public int provideContentRes() {
        return R.layout.app_settings;
    }

    @Override
    protected void onFragmentInVisible(Bundle savedInstanceState) {

    }

    @Override
    protected void onFragmentVisible(Bundle savedInstanceState) {

    }

    public void onDestroy(){
        super.onDestroy();
        UmengUpdateAgent.setUpdateListener(null);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        FPreferenceManager.putBoolean(MSConstants.KEY_UPLOAD_MODE_WIFI_ONLY, isChecked);
        DLog.w("upload", "tag:" + MSConstants.KEY_UPLOAD_MODE_WIFI_ONLY + buttonView.getTag() + "" + isChecked);
        if (MSConstants.KEY_MSG_NOTIFY.equals(buttonView.getTag())) {
            EMChatOptions options = EMChatManager.getInstance().getChatOptions();
            options.setNotificationEnable(isChecked);
        } else if (MSConstants.KEY_UPLOAD_MODE_WIFI_ONLY.equals(buttonView.getTag())) {
            UploadService.actionStart(this.getActivity());
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.relative_cutSetting:
                Bundle bundle = new Bundle();
                bundle.putString(ActionBarFragmentActivity.FRAGMENT_CLASS_NAME, ShortcutSettingFragment.class.getName());
                bundle.putInt(ActionBarFragmentActivity.FRAGMENT_TITLE, R.string.shortcuts_settings);
                Intent intent = new Intent(getActivity(), ActionBarFragmentActivity.class);
                intent.putExtras(bundle);
                getActivity().startActivity(intent);
                break;
            case R.id.relative_clearCache:
                ConfirmDialogFragment cleardialogFragment = ConfirmDialogFragment.newInstance(getActivity().getResources().getString(R.string.clear_cache), getActivity().getResources().getString(R.string.text_confirmto_clearcache));
                cleardialogFragment.setListener(this);
                cleardialogFragment.show(getFragmentManager(), "clearCache");
                break;
            case R.id.relative_feedBack:
                intent = new Intent(ContextManager.context(), WebActivity.class);
                intent.putExtra(FConstants.X5WEBVIEW_INITIAL_URL, MSConstants.APIConstants.FEED_BACK_URL);
                startActivity(intent);
                break;
        }
    }

    @Override
    public void doPositiveClick(String tag) {
        if ("clearCache".equals(tag)) {
            String size;
            String sysCache = getActivity().getCacheDir().getAbsolutePath();
            double sysSize = FileSizeHelper.getFileOrFilesSize(sysCache, FileSizeHelper.SIZETYPE_KB);
            String appCache = MSApplication.getDataDir() + "/cache";
            double appSize = FileSizeHelper.getFileOrFilesSize(appCache, FileSizeHelper.SIZETYPE_KB);
            double total = sysSize;
            FileHelper.delete(sysCache);
            if (!sysCache.equals(appCache)) {
                total += appSize;
                FileHelper.delete(appCache);
            }
            if (total > 1024) {
                total = total / 1024;
                size = String.format("%.2f", total) + "MB";
            } else {
                size = String.format("%.2f", total) + "KB";
            }
            Toast.makeText(getContext(), "一共清理了" + size + "垃圾", Toast.LENGTH_LONG).show();
        } else if (UPDATE_TAG.equals(tag)) {//友盟更新
            UmengUpdateAgent.forceUpdate(getActivity().getApplicationContext());
            UmengUpdateAgent.startDownload(getActivity(), updateResponse);
            Toast.makeText(getActivity(), "开始更新", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void doNegativeClick(String tag) {
    }

    @Override
    public void onUpdateReturned(int updateStatus, final UpdateResponse updateResponse) {
        if (update == null || updateResponse == null) return;
        switch (updateStatus) {
            case UpdateStatus.Yes: // has update
                if (updateResponse.hasUpdate) {
                    this.updateResponse = updateResponse;
                }
                tv_updateIcon.setVisibility(View.VISIBLE);
                update.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String versionCode = getActivity().getResources().getString(R.string.detected_new_version) + updateResponse.version;
                        String packageSize = getActivity().getResources().getString(R.string.update_packget_size) + String.format("%.2f", Double.valueOf(updateResponse.target_size) / 1048576) + "MB";
                        ConfirmDialogFragment updatedialogFragment = ConfirmDialogFragment.newInstance(versionCode, packageSize);
                        updatedialogFragment.setListener(AppSettingFragment.this);
                        updatedialogFragment.show(getFragmentManager(), UPDATE_TAG);
                    }
                });
                break;

        }
    }

    @Override
    public int getActionBarRightResourceId() {
        return 0;
    }

    @Override
    public int getActionBarRight2ResourceId() {
        return 0;
    }

    @Override
    public void onActionBarRight2Click() {

    }

    @Override
    public void onActionBarRightClick() {

    }
}

